package com.hzgj.bcl.soa.registry;

import com.hzgj.bcl.soa.config.RegistryDef;
import com.hzgj.bcl.soa.config.ServiceDef;
import com.hzgj.bcl.util.lang.StrKit;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;

import lombok.Builder;
import lombok.Getter;

/**
 * Created by dell on 2015/3/25.
 */
public class RegistryContext {

    private Map<String, RegistryFactory> registryMap = new HashMap<>();

    {
        ServiceLoader<RegistryFactory> serviceLoader = ServiceLoader.load(RegistryFactory.class);
        Iterator<RegistryFactory> it = serviceLoader.iterator();
        while (it.hasNext()) {
            RegistryFactory registryFactory = it.next();
            registryMap.put(registryFactory.getName(), registryFactory);
        }
    }

    private RegistryFactory lookup(RegistryDef registryDef) {
        String protocol = registryDef.getProtocol();
        if (StrKit.isBlank(protocol)) {
            throw new RuntimeException("Registry Factory protocol must be exist.");
        }
        return registryMap.get(protocol);
    }

    public Registry lookupRegistry(RegistryDef registryDef) {
        return lookup(registryDef).getRegistry(registryDef);
    }

    public RegistryUpdater lookupRegistryUpdater(RegistryDef registryDef) {
        return lookup(registryDef).getRegistryUpdater(registryDef);
    }

    @Builder
    @Getter
    public static class ServerRegisterModel {
        private Map<String, ServiceDef.Attr> services;
        private String serverId;
    }
}
